<template>
  <Selector
    v-model="sonValue"
    v-bind="$attrs"
    v-on="$listeners"
    :options="list"
    :multiple="multiple"
    @changed="onChange"
    label-name="title"
    value-name="id"
    filterable
  >
  </Selector>
</template>

<script>
import Selector from "@/components/yjj/Selector"
import { getList } from "@/api/triones/activity";
export default {
  name: "index",
  components: {
    Selector
  },
  props: {
    value: {
      type: [String,Number,Array],
      default: ''
    },
    retrunType: {
      type: String,
      default: 'string'
    },
    multiple: {
      type: Boolean,
      default: false
    },
    syncKeys: {
      type: Array,
      default: () => []
    },
    memberId: {
      type: Number,
      default: undefined
    },
    defaultFirst: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      list: []
    }
  },
  computed: {
    sonValue: {
      get() {
        if (this.multiple) {
          if (this.value) {
            if (this.value instanceof Array) {
              return this.value;
            } else {
              const strList = this.value.split(",") || [];
              const numberList = strList.map(i => Number(i));
              return numberList;
            }
          } else {
            return this.value
          }
        } else {
          return this.value
        }
      },
      set(val) {
        if (this.retrunType === 'string' && val instanceof Array) {
          this.$emit('input', val.join(","))
        } else {
          this.$emit('input', val)
        }
      }
    }
  },
  mounted() {
    this.Get_List()
  },
  methods: {
    Get_List() {
      const params = {
        memberId: this.memberId
      }
      getList(params).then(response => {
        this.list = response.data;
        if (this.defaultFirst) {
          this.sonValue = this.list[0].id;
        }
      }).catch(e => {
        this.list = []
      })
    },
    onChange(val) {
      if (this.retrunType === 'string' && val instanceof Array) {
        this.$emit('input', val.join(","))
      } else {
        this.$emit('input', val)
      }
      if (this.multiple) {
        let selectedItems =  this.list.filter(item => val.includes(item.userId))
        this.$emit('changed', selectedItems)
        this.syncKeys.forEach(key => {
          this.$emit(`update:${key}`, selectedItems.map(i => i[key]).join(","));
        })
      } else {
        this.$emit('changed', val)
        this.syncKeys.forEach(key => {
          this.$emit(`update:${key}`, val[key]);
        })
      }
    }
  }
}
</script>

<style scoped>

</style>
